const fs = require('fs');
const path = require('path');

// 创建日志目录
const logDir = path.join(__dirname, '../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

class Logger {
  constructor() {
    this.logFile = path.join(logDir, 'app.log');
    this.errorFile = path.join(logDir, 'error.log');
    this.authFile = path.join(logDir, 'auth.log');
  }

  formatMessage(level, message, metadata = {}) {
    const timestamp = new Date().toISOString();
    const metaStr = Object.keys(metadata).length > 0 ? ` | ${JSON.stringify(metadata)}` : '';
    return `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}\n`;
  }

  writeToFile(filename, message) {
    try {
      fs.appendFileSync(filename, message);
    } catch (error) {
      console.error('Failed to write to log file:', error);
    }
  }

  info(message, metadata = {}) {
    const logMessage = this.formatMessage('info', message, metadata);
    console.log(`ℹ️ ${message}`, metadata);
    this.writeToFile(this.logFile, logMessage);
  }

  error(message, error = null, metadata = {}) {
    const errorData = error ? {
      message: error.message,
      stack: error.stack,
      ...metadata
    } : metadata;
    
    const logMessage = this.formatMessage('error', message, errorData);
    console.error(`❌ ${message}`, errorData);
    this.writeToFile(this.errorFile, logMessage);
    this.writeToFile(this.logFile, logMessage);
  }

  warn(message, metadata = {}) {
    const logMessage = this.formatMessage('warn', message, metadata);
    console.warn(`⚠️ ${message}`, metadata);
    this.writeToFile(this.logFile, logMessage);
  }

  debug(message, metadata = {}) {
    if (process.env.NODE_ENV === 'development' || process.env.DEBUG) {
      const logMessage = this.formatMessage('debug', message, metadata);
      console.debug(`🐛 ${message}`, metadata);
      this.writeToFile(this.logFile, logMessage);
    }
  }

  auth(message, metadata = {}) {
    const logMessage = this.formatMessage('auth', message, metadata);
    console.log(`🔐 ${message}`, metadata);
    this.writeToFile(this.authFile, logMessage);
    this.writeToFile(this.logFile, logMessage);
  }

  // 获取最新日志
  getRecentLogs(lines = 50) {
    try {
      const logs = fs.readFileSync(this.logFile, 'utf8');
      return logs.split('\n').slice(-lines).filter(line => line.trim());
    } catch (error) {
      return ['日志文件不存在或无法读取'];
    }
  }

  // 搜索特定日志
  searchLogs(keyword, filename = this.logFile) {
    try {
      const logs = fs.readFileSync(filename, 'utf8');
      return logs.split('\n').filter(line => 
        line.toLowerCase().includes(keyword.toLowerCase())
      );
    } catch (error) {
      return [];
    }
  }
}

module.exports = new Logger(); 